package com.tinymall.common.exception.handler;

import com.tinymall.common.exception.ServiceException;
import com.tinymall.common.exception.UserExistException;
import com.tinymall.common.restful.ResponseData;
import com.tinymall.common.restful.ResponseDataUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ServiceException.class)
    public ResponseData handleServiceException(ServiceException ex) {
        return ResponseDataUtils.buildError("0",ex.getMessage());
    }

    @ExceptionHandler(BindException.class)
    public ResponseData handleBindException(BindException ex) {
        List<FieldError> fieldErrors = ex.getBindingResult().getFieldErrors();
        StringBuilder stringBuilder = new StringBuilder();
        for (FieldError fieldError : fieldErrors) {
            stringBuilder.append("；");
            stringBuilder.append(fieldError.getDefaultMessage());
        }
        String message = stringBuilder.substring(1);
        return ResponseDataUtils.buildError("2",message);
    }
    @ExceptionHandler(UserExistException.class)
    public ResponseData handleUserExistException(UserExistException ex) {
        System.out.println("进入用户已存在异常了！！！！");
        return ResponseDataUtils.buildError("1",ex.getMessage());
    }

}
